package com.dlwx.parttimetalent.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.ContactsAdapter;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.ContactsBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.PositionInter;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class ContactsActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private ContactsAdapter mAdapter;
    private RxPermissions rxPermission;

    /**
     * 获取库Phone表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};


    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME = 0;

    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER = 1;

    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID = 2;

    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID = 3;

    /**
     * 联系人名称
     **/
    private ArrayList<String> mContactsName = new ArrayList<String>();

    /**
     * 联系人头像
     **/
    private ArrayList<String> mContactsNumber = new ArrayList<String>();

    /**
     * 联系人头像
     **/
    private ArrayList<Bitmap> mContactsImg = new ArrayList<Bitmap>();
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        ButterKnife.bind(this);
        initView();
        rxPermission = new RxPermissions(this);
        rxPermission.request(Manifest.permission.READ_CONTACTS)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            getPhoneContacts();
                        } else {
                            startActivity(new Intent(ContactsActivity.this, MainActivity.class));
                        }
                    }
                });
    }

    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("添加通讯录好友");

    }


    // 获取手机联系人
    private void getPhoneContacts() {
        String phonenoStr = "";
        // rely=(RelativeLayout) findViewById(R.id.relationId);
        ContentResolver resolver = getContentResolver();

        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                PHONES_PROJECTION, null, null, null);

        // 不为空
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER);
                phoneNumber=phoneNumber.replace(" ","");
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;

                // 得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME);

                // 得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID);

                // 得到联系人头像ID
                Long imgid = phoneCursor.getLong(PHONES_PHOTO_ID);

                // 得到联系人头像Bitamp
                Bitmap bitmap = null;

                // photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                try {
                    if (imgid > 0) {
                        Uri uri = ContentUris.withAppendedId(
                                ContactsContract.Contacts.CONTENT_URI, contactid);
                        InputStream input = ContactsContract.Contacts
                                .openContactPhotoInputStream(resolver, uri);
                        bitmap = BitmapFactory.decodeStream(input);
                    } else {
                        // 设置默认
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.icon_zhucenvshen);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                ContactsBean bean = new ContactsBean();
                if (!TextUtils.isEmpty(contactName)) {
                    phonenoStr=phonenoStr+phoneNumber+"@@"+contactName+"##";
                }
            }
            phoneCursor.close();
            if(phonenoStr.endsWith("##")){
                phonenoStr=phonenoStr.substring(0,phonenoStr.length()-2);
            }
            getDatas(phonenoStr);
        }
    }

    private void getDatas(String phonenoStr) {
        loadingDialog.show();
        OkgoUtil.post(Http.FriendList,ContactsActivity.this)
                .params("phonenoStr",phonenoStr)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        ContactsBean parentBean= DealResult.getInstance().dealDatas(ContactsActivity.this
                                ,response,new TypeToken<ContactsBean>() {}.getType());
                        if(parentBean==null){return;}
                        int code=parentBean.getCode();
                        if(code== Constant.SUCESS){
                            setDatas(parentBean.getBody());
                        }else {
//                            ToastUtils.toastForShort(ContactsActivity.this,parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        loadingDialog.dismiss();
                        super.onError(response);
                        ToastUtils.toastForShort(ContactsActivity.this,getString(R.string.bad_net));
                    }
                });
    }

    private void setDatas(List<ContactsBean.BodyBean> body) {
//        mAdapter.addAll(body);
//        recyclerView.refreshComplete(mAdapter.getItemCount());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactsAdapter(this, new PositionInter() {
            @Override
            public void callBack(int position) {
                doAttention(mAdapter.getDataList().get(position).getUserid()+"",position);
            }
        });
        mAdapter.setDataList(body);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        //divider
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.size_1)
//                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.bg)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(false);
        tvContent.setText(mAdapter.getItemCount()+"位好友可添加");
    }

    @OnClick({R.id.tv_confirm,R.id.title_left_one_btn})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.title_left_one_btn:
                    this.finish();
                    break;
                case R.id.tv_confirm:
                    startActivity(new Intent(this,MainActivity.class));
                    break;
            }
        }

    private void doAttention(String curruserId, final int position) {
        OkgoUtil.post(Http.FollowUser, this)
                .params("followuserid", curruserId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseBean parentBean = DealResult.getInstance().dealDatas(ContactsActivity.this, response, new TypeToken<BaseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            mAdapter.remove(position);
                            tvContent.setText(mAdapter.getItemCount()+"位好友可添加");
                        } else {
                        }
                        ToastUtils.toastForShort(ContactsActivity.this, parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(ContactsActivity.this, getString(R.string.bad_net));
                    }
                });
    }
}
